<?php

namespace app\index\controller\access;

use app\common\model\MemberToken;
use app\index\service\AccessService;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use think\APP;
use think\Request as Request;

/**
 * Access 控制器
 * Class Access
 * @package app\index\controller\access;
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037509
 */
class Access
{
    // 请求参数
    private Request $request;

    // service
    private AccessService $service;

    public function __construct(Request $request, AccessService $accessService)
    {
        $this->request = $request;
        $this->service = $accessService;
    }

    /**
     * 客户端访问记录
     * @return ApiResponse
     * @url /access/access/save
     */
    public function save(): ApiResponse
    {
        $request = $this->request;

        $referer = $request->param('referer', '');
        $pagePath = $request->param('pagePath', '');
        $ip = $request->ip();
        $memberId = $this->getMemberId();

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        $this->service->add($referer, $pagePath, $ip, $memberId, $pf, $chain, $promotionGroupId);

        return ApiResponse::success(null);
    }

    private function getMemberId()
    {
        $token = $this->request->header('token', $this->request->param('token'));
        if (is_blank($token)) {
            return 0;
        }
        return MemberToken::where('token', $token)->value('memberId', 0);
    }

}
